/**
 * 目标1：信息渲染
 *  1.1 获取用户的数据
 *  1.2 回显数据到标签上
 * */

const creator = '周杰伦'
axios({
    url: 'https://hmajax.itheima.net/api/settings',
    params: {
        creator
    }
}).then((result) => {
    console.log(result.data);
    const keys = Object.keys(result.data.data)
    keys.forEach(item => {
        if (item === 'avatar') {
            document.querySelector('.prew').src = result.data.data[item]
        } else if (item === 'gender') {
            const genders = document.querySelectorAll('.gender')
            genders[result.data.data[item]].checked = true
        } else {
            document.querySelector(`.${item}`).value = result.data.data[item]
        }
    })
})

/**
 * 修改头像
 */
document.querySelector('.upload').addEventListener('change', (e) => {
    const fd = new FormData()
    fd.append('avatar', e.target.files[0])
    fd.append('creator', creator)

    axios({
        url: 'https://hmajax.itheima.net/api/avatar',
        method: 'PUT',
        data: fd
    }).then(res => {
        document.querySelector('.prew').src = res.data.data.avatar
    })
})

/**
 * 修改信息
 */

document.querySelector('.submit').addEventListener('click', () => {
    const form = document.querySelector('.user-form')
    const params = serialize(form, { hash: true, empty: true })
    params['creator'] = creator
    params.gender = +params.gender
    axios({
        url: 'https://hmajax.itheima.net/api/settings',
        method: 'PUT',
        data: params
    }).then(res => {
        const toastDom = document.querySelector('.my-toast')
        const toast = new bootstrap.Toast(toastDom)
        toast.show()
    })
})